package com.lt.flashcard.view;

import org.apache.log4j.Logger;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.Init;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.zk.ui.Executions;

import com.lt.flashcard.Utility;
import com.lt.flashcard.model.service.AAService;
import com.lt.flashcard.model.service.Repository;

public class LoginCtrl {

    private String username = "";
    private String password = "";
    private String message = "";
    private String dest = "";
    private Boolean remember = false;

    private static final Logger log = Logger.getLogger(LoginCtrl.class);

    @Init
    public void init() {
        AAService srv = Repository.getInstance().getAAService();
        if (srv.isLogin()) {
            Executions.sendRedirect("/wordlist.zul");
        }
        dest = Executions.getCurrent().getParameter("dest");
        if (!Utility.isEmptyString(dest)) {
            Utility.rememberPage(dest);
        }
    }

    @NotifyChange("message")
    @Command("login")
    public void doLogin() {
        AAService srv = Repository.getInstance().getAAService();
        try {
            if (!srv.doLogin(getUsername(), getPassword(), remember, true)) {
                log.info("Remember: " + remember);
                message = "* Tên đăng nhập hoặc mật khẩu không đúng";
            }
        } catch (Exception e) {
            log.error("Cant' login", e);
            message = "* Tên đăng nhập hoặc mật khẩu không đúng";
        }
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Boolean getRemember() {
        return remember;
    }

    public void setRemember(Boolean remember) {
        this.remember = remember;
    }
}
